
import React, { useState } from 'react';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import {HTML5Backend} from 'react-dnd-html5-backend';

const ITEM_TYPES = {
  DRAGGABLE_ITEM: 'draggable_item',
};

const DraggableItem = ({ id, text }) => {
  const [{ isDragging }, drag] = useDrag({
    type: ITEM_TYPES.DRAGGABLE_ITEM,
    item: { id,text },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });

  return (
    <div ref={drag} style={{ opacity: isDragging ? 0.5 : 1 }}>
      {text}
    </div>
  );
};

const DropZone = ({ onDrop,items2 }) => {
  const [{ canDrop, isOver }, drop] = useDrop({
    accept: ITEM_TYPES.DRAGGABLE_ITEM,
    drop: (item) => onDrop(item),
    collect: (monitor) => ({
      isOver: monitor.isOver(),
      canDrop: monitor.canDrop(),
    }),
  });

  let backgroundColor = '';
  if (isOver && canDrop) {
    backgroundColor = 'lightgreen';
  } else if (isOver && !canDrop) {
    backgroundColor = 'pink';
  }
  console.log('items2',items2)
  return (
    <div ref={drop} style={{ padding: '20px', backgroundColor }}>
      Drop here!
      {items2.map((item) => (
              <div key={item.id}>{item.text}</div>
            ))}      
    </div>
  );
};


function App() {
  const [items0, setItems0] = useState([
    { id: 4, text: 'Item 4' },
    { id: 5, text: 'Item 5' },
    // ...
  ]);
  const [items, setItems] = useState([
    { id: 1, text: 'Item 1' },
    { id: 2, text: 'Item 2' },
    // ...
  ]);
  const [items2, setItems2] = useState([
  ]);

  const handleDrop = (droppedItem) => {
    const newItems1 = items.filter((item) => item.id !== droppedItem.id);
    const newItems0 = items0.filter((item) => item.id !== droppedItem.id);
    setItems([...newItems1]);
    setItems0([...newItems0]);
    setItems2([...items2,droppedItem])
  };

  return (
    <DndProvider backend={HTML5Backend}>
      <div >
        <div>
          <h2>Draggable Items 0</h2>
          <ul>
            {items0.map((item) => (
              <DraggableItem key={item.id} id={item.id} text={item.text} />
            ))}
          </ul>
        </div>
        <div>
          <h2>Draggable Items 1</h2>
          <ul>
            {items.map((item) => (
              <DraggableItem key={item.id} id={item.id} text={item.text} />
            ))}
          </ul>
        </div>
        <div>
          <h2>Drop Zones</h2>
          <DropZone onDrop={handleDrop} items2={items2}/>
          {/* 添加更多 DropZone 组件 */}
        </div>
      </div>
    </DndProvider>
  );
}

export default App;
